package com.oauth2.exception;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

import java.io.IOException;
import java.util.Map;

public class CustomOauthExceptionSerializer extends StdSerializer<CustomOauthException> {
    public CustomOauthExceptionSerializer() {
        super(CustomOauthException.class);
    }

    @Override
    public void serialize(CustomOauthException value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeStartObject();
        gen.writeNumberField("code", 401);
        String message = value.getMessage().split(":")[0];
        if (message.equals("Invalid refresh token")) {
            gen.writeStringField("msg", "刷新Token无效！");
        } else if (message.equals("Invalid authorization code")) {
            gen.writeStringField("msg", "无效的令牌码！");
        } else if (message.equals("Bad credentials")) {
            gen.writeStringField("msg", "错误的凭据！");
        } else if (message.equals("Token was not recognised")) {
            gen.writeStringField("msg", "无效的Token！");
        } else {
            gen.writeStringField("msg", "服务发生错误,请重试！");
        }
        if (value.getAdditionalInformation() != null) {
            for (Map.Entry<String, String> entry : value.getAdditionalInformation().entrySet()) {
                String key = entry.getKey();
                String add = entry.getValue();
                gen.writeStringField(key, add);
            }
        }
        gen.writeEndObject();
    }
}
